package org.aurora.daily;

import org.springframework.stereotype.Component;

import java.util.concurrent.RecursiveTask;

/**
 * @author : qiaodan
 * @date : 2024/8/27 11:07
 * @description ForkJoin测试案例 大数相加（1-1_0000_0000）
 */

public class MyForkJoinTask extends RecursiveTask<Long> {
    private static Long THRESHOLD = 10000L;
    private final Long start;
    private final Long end;

    public MyForkJoinTask(long start, long end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        Long length = end - start;
        if(length <= THRESHOLD){
            return sumNumber();
        }
        long middle = (start + end) >>> 1;
        MyForkJoinTask leftTask = new MyForkJoinTask(start, middle);
        MyForkJoinTask rightTask = new MyForkJoinTask(middle + 1, end);
        //拆分左边任务
        leftTask.fork();
        //拆分右边任务
        rightTask.fork();
        //合并返回结果
        return leftTask.join() + rightTask.join();
    }


    public Long sumNumber(){
        long sum = 0;
        for(long i=start; i<=end; ++i){
            sum += i;
        }
        return sum;
    }
}
